package com.mornstar.common.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.google.common.base.Functions;

import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;

import static java.util.stream.Collectors.toMap;

/**
 * 系统设置 - 多数据源相关
 *
 * @author xiekun
 * @version 1.0
 * */

public enum DbType {
	MYSQL(0, "mysql"),
	ORACLE(1, "oracle"),
	SQLSERVER(2, "sqlserver"),
	DB2(3, "db2");

	@EnumValue
	private final int code;

	/**
	 * 类型描述
	 **/
	private final String descp;

	DbType(int code, String descp) {
		this.code = code;
		this.descp = descp;
	}

	public int getCode() {
		return code;
	}

	public String getDescp() {
		return descp;
	}

	private static final Map<Integer, DbType> DB_TYPE_MAP =
		Arrays.stream(DbType.values()).collect(toMap(DbType::getCode, Functions.identity()));

	public static DbType of(int type) {
		if (DB_TYPE_MAP.containsKey(type)) {
			return DB_TYPE_MAP.get(type);
		}
		return null;
	}

	/**
	 * 根据名称查找对应的数据源
	 *
	 * @param name 数据源名称
	 * @return DbType
	 */
	public static DbType ofName(String name) {
		return Arrays.stream(DbType.values()).filter(e -> e.name().equals(name)).findFirst().orElseThrow(() -> new NoSuchElementException("no such db type"));
	}
}
